<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./vue.js"></script>
  <style>
    button{
      position: fixed;
      bottom:100px;
      right:50px;
      display:none;
    }
  </style>
</head>
<body style="height: 3000px;">
  <div id="app">
    <button v-scroll="500">回到顶部</button>
   
  </div>
  <script>
    Vue.directive("scroll",{
      inserted(el,binding){
        // 获取传入的值
        let scrollTop = binding.value;
        console.log(scrollTop);
        // 绑定一个事件
        window.onscroll = function(){
          // 获取滚动距离
          var sTop = document.documentElement.scrollTop||document.body.scrollTop;
          if(sTop > scrollTop){
            el.style.display = "block"
          }else{
            el.style.display = "none"
          }
        }
        el.onclick = function(){
          window.scrollTo(0,0);
        }
      },
      unbind(){
        // 如果在 inserted 如创建了定时器没清楚、或者绑定了全局事件 做清楚定时器，移除全局事件..
        window.onscroll = null;
      }
    })
    let vm = new Vue({
      el:"#app",

    })
  </script>
</body>
</html>